import React, { useMemo } from 'react'
import Taro from '@tarojs/taro'
import { Text, View, Image } from '@tarojs/components'
import Navigate from '@NAVIGATION/navigateManager'
import { DECISION_TYPE } from '@CONSTANTS/decision'
import { Analytic_Type } from '@CONSTANTS/analytic'
import Images from '@ASSET/Images'
import { StringMapAnyITF } from '@INTERFACES/Common'
import { PLAN_ENTITY_TYPE_ENUM } from '@CONSTANTS/planManagement'
import { DailyContentITF } from '@INTERFACES/PlanManagement'
import i18n from '@I18N'
import { STORAGE_KEY } from '@CONSTANTS/common'
import { setGlobalData } from '@UTILS/globalData'
import style from './PlanCardItem.module.scss'

interface ClickDataITF {
  eId: string
  resultId: string
  day: number
  planId: string
  viewed: boolean
  isToday?: boolean
  currentDate?: string
}

interface Props {
  data: DailyContentITF
  onHandler: (entityId: string) => void
  day: number
  planId: string
  currentDay: number
  isFirst: boolean
  currentDate?: string
}

const MAPS: StringMapAnyITF = {
  [PLAN_ENTITY_TYPE_ENUM.FeedItem]: {
    title: '文章',
    tip: '点击查看',
    icon: 'feed_item',
    onClick: ({ eId, viewed, planId, day, isToday }: ClickDataITF) => {
      const params = { id: eId }
      if (!viewed && isToday) {
        Object.assign(params, { planId, day, showTransition: true })
      }
      Navigate.feedDetail(params)
    }
  },
  [PLAN_ENTITY_TYPE_ENUM.Survey]: {
    title: '调查问卷',
    tip: '点击填写',
    icon: 'survey',
    onClick: ({ eId, resultId, day, planId }: ClickDataITF) => {
      if (resultId) {
        Navigate.surveyDetail({ sId: resultId })
      } else {
        Navigate.surveyDetail({ tId: eId, day, planId, showTransition: true })
      }
    }
  },
  [PLAN_ENTITY_TYPE_ENUM.DecisionFlow]: {
    title: '调查问卷',
    tip: '点击填写',
    icon: 'survey',
    onClick: ({ eId, resultId, day, planId }: ClickDataITF) => {
      if (resultId) {
        Navigate.decisionResultPage({
          id: resultId,
          isSurvey: false
        })
      } else {
        Navigate.decisionFlowIndex({
          id: resultId,
          dId: eId,
          type: DECISION_TYPE.Decision,
          day,
          planId,
          showTransition: true
        })
      }
    }
  },
  [PLAN_ENTITY_TYPE_ENUM.Course]: {
    title: '视频',
    tip: '点击查看',
    icon: 'video',
    onClick: ({ eId, viewed, planId, day, isToday }: ClickDataITF) => {
      const params = { id: eId, isPlanTask: true, isToday, day }
      if (!viewed && isToday) {
        Object.assign(params, { planId, day, showTransition: true })
      }
      Navigate.videoDetail(params)
    }
  },
  [PLAN_ENTITY_TYPE_ENUM.PainLog]: {
    title: '疼痛日志',
    tip: '点击填写',
    icon: 'log',
    onClick: ({ resultId, currentDate }: ClickDataITF) => {
      setGlobalData('logDateBucket', currentDate)
      Navigate.switchTab('dataCenter')
    }
  },
  [PLAN_ENTITY_TYPE_ENUM.Meditation]: {
    title: '冥想系列',
    tip: '开始冥想',
    icon: 'meditation',
    onClick: ({ viewed, isToday }: ClickDataITF) => {
      Taro.setStorageSync(STORAGE_KEY.meditation_is_today, isToday)
      if (viewed) {
        Navigate.meditation()
      } else {
        Navigate.meditation({ showTransition: true })
      }
    }
  },
  [PLAN_ENTITY_TYPE_ENUM.DesignatedMeditation]: {
    title: '冥想系列',
    tip: '开始冥想',
    icon: 'meditation',
    onClick: ({ viewed, eId, isToday }: ClickDataITF) => {
      const params = { id: eId }
      Taro.setStorageSync(STORAGE_KEY.meditation_is_today, isToday)
      if (!viewed) {
        Object.assign(params, { showTransition: true })
      }
      Navigate.meditationDetail(params)
    }
  }
}
const getImageSrc = (type: PLAN_ENTITY_TYPE_ENUM) => {
  const name = MAPS[type]?.icon
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  return Images.managePlan[`icon_task_${name}`]
}
const convertSecToMin = (sec: number): string => {
  const minStr = ((sec || 0) / 60).toFixed(1)
  return `${Number(minStr)}`
}
const PlanCardItem: React.FC<Props> = ({ data, onHandler, day, planId, currentDay, isFirst, currentDate }) => {
  const language = 'zh'
  const {
    Title, DisplayTitle, EntityId, EntityType, Viewed, Disabled, ActionRequired, ResultEntityId,
    ReminderHour, Description, Length, FinishedTime = 0, Important
  } = data

  const title = DisplayTitle?.[language] || Title?.[language]
  const isBefore = day < currentDay
  const isToday = day === currentDay
  const isAfter = day > currentDay
  const disabled = !isToday || Disabled
  const disabledClick = isAfter || Disabled
  const iconSrc = getImageSrc(EntityType)
  const onCallback = () => {
    !ActionRequired && !Viewed && currentDay === day && onHandler?.(EntityId)
  }
  const onClick = async () => {
    if (disabledClick) return
    Taro.tracker.trackEvent(Analytic_Type.tap_plan_card.eventId, { title })
    MAPS?.[EntityType].onClick?.({ eId: EntityId, resultId: ResultEntityId, day, planId, viewed: Viewed, isToday, currentDate })
    ![PLAN_ENTITY_TYPE_ENUM.Course, PLAN_ENTITY_TYPE_ENUM.FeedItem].includes(EntityType) && onCallback()
  }
  const btnText = useMemo(() => {
    if (isBefore) {
      return Disabled ? i18n.plan.disabled() : i18n.plan.toSee()
    }
    if (isToday) {
      return Viewed ? i18n.plan.toSee() : i18n.plan.toComplete()
    }
    return i18n.plan.toComplete()
  }, [Disabled, Viewed, isBefore, isToday])
  const isDisabledStyle = disabled || Viewed
  const isDisabledBtn = isBefore ? Disabled : isDisabledStyle
  const hasTheme = isFirst && isToday
  const isDone = Viewed && !Disabled
  const importantImage = isDisabledStyle ? Images.managePlan.mustDoIconClosed : Images.managePlan.mustDoIcon
  const isMeditation = [PLAN_ENTITY_TYPE_ENUM.DesignatedMeditation, PLAN_ENTITY_TYPE_ENUM.Meditation].includes(EntityType) && Length > 0
  return (
    <View className={style.container} onClick={onClick}>
      <View className={style.commonPlanCard}>
        <Image src={iconSrc} className={style.image} />
        <View className={style.content}>
          <View className={style.titleCard}>
            <Text className={`${style.title} ${isDisabledStyle ? style.disabledText : ''}`}>
              {title}
            </Text>
            <View className={style.downIconBox}>
              {isDone && <Image src={Images.managePlan.icon_plan_done} className={style.doneIcon} />}
            </View>
          </View>

          <View className={style.bottom}>
            <View className={style.tipsContainer}>
              {!!Important && <Image src={importantImage} className={style.importantContainer} />}
              {
                isMeditation && (
                  <View className={`${style.minDesc} ${isDisabledStyle ? style.disabledC2Text : ''}`}>
                    <Text className={isDisabledStyle ? '' : style.themeText}>{`${convertSecToMin(Math.min(FinishedTime, Length))}`}</Text>
                    <Text>{`/${convertSecToMin(Length)}分钟`}</Text>
                  </View>
                )
              }
              <View className={style.descText}>
                <Text
                  className={`${style.tips} ${isDisabledStyle ? style.disabledC2Text : ''}`}
                >
                  {Description}
                </Text>
              </View>
            </View>
            {
              isDone ? (
                <View className={style.viewedBtn}>
                  <Text className={style.viewedBtnText}>{btnText}</Text>
                </View>
              ) : (
                <View className={`${hasTheme ? style.themeBtn : style.normalBtn} ${isDisabledStyle ? style.disabledBtn : ''}`}>
                  <Text className={`${hasTheme ? style.firstText : style.btnText2} ${isDisabledBtn ? style.disabledC2Text : ''}`}>
                    {btnText}
                  </Text>
                </View>
              )
            }
          </View>
        </View>
      </View>
    </View>
  )
}

export default PlanCardItem
